package com.example.demo;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by vincent on 2018/5/9.
 */
@RestController
public class HelloController {
    private final Logger logger = LoggerFactory.getLogger(HelloController.class);


    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/add" ,method = RequestMethod.GET)
    public Integer add(@RequestParam Integer a, @RequestParam Integer b) {
        List<ServiceInstance> instances = client.getInstances("compute-service");
        ServiceInstance instance = instances.get(0);
        Integer r = a + b;
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
        return r;
    }

    @GetMapping("/hello")
    public String hello(){
        List<ServiceInstance> instances = client.getInstances("compute-service");
        ServiceInstance instance = instances.get(0);
        logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
        return "hello";
    }

    @PostMapping(value = "/sayMyName")
    public Map<String,Object> sayMyName(@RequestBody User user){
        Map<String, Object> map = new HashMap<>();
        logger.info("name=" + user.getName());
        logger.info("age=" + user.getAge());
        map.put("name", user.getName());
        map.put("age", user.getAge());
        return map;
    }

}
